package com.flycms.module.app.service;

import com.flycms.core.entity.PageVo;
import com.flycms.module.app.dao.AppDao;
import com.flycms.module.app.dao.AppDetailDao;
import com.flycms.module.app.enums.AppUpdateType;
import com.flycms.module.app.model.App;
import com.flycms.module.app.model.AppDetail;
import com.flycms.module.app.param.AppQueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Objects;

/**
 * @author mdoenglang
 */

@Service
public class AppService {

    @Autowired
    private AppDao appDao;
    @Autowired
    private AppDetailDao appDetailDao;

    /**
     * 获取最热Apps
     *
     * @return 最热Apps结果集
     */
    public List<App> getHotAppList() {
        return appDao.getHotAppList();
    }

    public PageVo<App> getAppPage(AppQueryParam param) {
        //统计
        int count = appDao.count(param);
        if (count <= 0) {
            return new PageVo<>(param.getPage());
        }
        //查询
        List<App> apps = appDao.selectByParam(param, (param.getPage() - 1) * param.getPageSize(), param.getPageSize());
        return new PageVo<>(param.getPage(), count, apps);
    }

    /**
     * 根据ID查询详情
     *
     * @return APP详情
     */
    public AppDetail getAppById(Long id) {
        return appDetailDao.selectByAppId(id);
    }

    /**
     * 修改APP统计数据
     *
     * @param i     1 点击数  2评论数
     * @param appId
     */
    public void updateCount(int i, Long appId) {
        if (AppUpdateType.HIT.getCode() == i) {
            appDao.updateHit(appId);
        }
        if (AppUpdateType.EVAL.getCode() == i) {
            appDao.updateEval(appId);
        }
    }

    /**
     * 新增app
     *
     * @param app 数据
     */
    @Transactional(rollbackOn = Exception.class)
    public void save(App app) {
        appDao.insertSelective(app);
        AppDetail appDetail = app.getAppDetail();
        appDetail.setAppId(app.getId());
        appDetailDao.insertSelective(appDetail);
    }

    /**
     * 修改app
     *
     * @param app 数据
     */
    @Transactional(rollbackOn = Exception.class)
    public void update(App app) {
        appDao.updateSelective(app);
        AppDetail appDetail = app.getAppDetail();
        if (Objects.isNull(appDetail)) {
            return;
        }
        appDetailDao.updateSelective(appDetail);
    }

    /**
     * 删除app
     *
     * @param id id
     */
    @Transactional(rollbackOn = Exception.class)
    public void del(Long id) {
        appDao.del(id);
        appDetailDao.del(id);
    }

    /**
     * 详细app信息
     *
     * @param id ID
     * @return app详细数据
     */
    public App getAppDetailById(Long id) {
        App app = appDao.selectById(id);
        if(Objects.isNull(app)){
            return null;
        }
        AppDetail appDetail = appDetailDao.selectByAppId(id);
        app.setAppDetail(appDetail);
        return app ;
    }
}
